package com.supkong.prototype.deep;

import lombok.Data;

import java.io.*;

/**
 * @author Kong
 * @date 2019/01/02
 * describe:
 */
@Data
public class Apple extends Fruit implements Cloneable, Serializable {
    private IPhone iPhone;

    public Apple() {
        this.iPhone = new IPhone();
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        // 浅克隆
        //return super.clone();
        //深克隆
        return this.deepClone();
    }

    private Object deepClone() {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);

            Apple apple = (Apple) ois.readObject();
            return apple;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }


    public Apple copy(Apple target){
        Apple apple = new Apple();
        apple.setHeight(target.getHeight());
        apple.setWeight(target.getWeight());
        apple.setName(target.getName());

        IPhone iPhone = new IPhone();
        iPhone.setName(apple.getIPhone().getName());
        iPhone.setWeight(apple.getIPhone().getWeight());
        apple.setIPhone(iPhone);
        return  apple;
    }
}
